/*
 * Created on 2005-8-5
 *
 */
package bma.common.langutil.convert.common;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;

import bma.common.langutil.convert.ConvertManager;
import bma.common.langutil.convert.Converter;
import bma.common.langutil.core.ClassUtil;
import bma.common.langutil.core.DateTimeUtil;
import bma.common.langutil.core.ExceptionUtil;

/**
 * 转换DateFormat数据
 * 
 * @author guanzhong
 *  @since 1.0 (imported from BMA.ESP Project)
 * 
 */
public class DateFormatConverter implements Converter, Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public static final DateFormatConverter DATE_TIME = new DateFormatConverter(
			DateTimeUtil.DATETIME_FORMAT);

	public static final DateFormatConverter DATE = new DateFormatConverter(
			DateTimeUtil.DATE_FORMAT);

	private String format;

	public DateFormatConverter() {
		super();
	}

	/**
	 * @param format
	 */
	public DateFormatConverter(String format) {
		super();
		this.format = format;
	}

	public String getFormat() {
		return this.format;
	}

	public void setFormat(String format) {
		this.format = format;
	}

	@Override
	public boolean canConvert(Class from, Class to) {
		return ConvertManager.isType(from, to, String.class, Date.class);
	}

	@Override
	public Object convertTo(Object src, Class to) {
		if (src instanceof String && ClassUtil.isExtendFrom(to, Date.class)) {
			String o = (String) src;
			SimpleDateFormat sdf = new SimpleDateFormat(this.format);
			try {
				return sdf.parse(o);
			} catch (Exception e) {
				throw ExceptionUtil.throwRuntime(e);
			}
		}
		if (src instanceof Date && ClassUtil.isExtendFrom(to, String.class)) {
			Date o = (Date) src;
			SimpleDateFormat sdf = new SimpleDateFormat(this.format);
			return sdf.format(o);
		}
		return null;
	}

}
